package com.sim.stream.simclient;

import com.sim.client.ImClientChannelContext;
import com.sim.client.SimClient;
import com.sim.client.SimClientAPI;
import com.sim.client.config.ImClientConfig;
import com.sim.core.packets.*;
import com.sim.core.tcp.TcpPacket;
import com.sim.core.utils.PropUtil;
import org.springframework.stereotype.Component;
import org.tio.core.Node;

/**
 * @author yzf
 */
@Component
public class ImStreamClient {
    private static ImClientChannelContext imClientChannelContext = null;
    public static void init()throws Exception {
        if (imClientChannelContext == null) {
            //服务器节点
            Node serverNode = new Node(PropUtil.get("sim.server.ip"),PropUtil.getInt("sim.server.port"));
            //构建客户端配置信息
            ImClientConfig imClientConfig = ImClientConfig.newBuilder()
                    //客户端业务回调器,不可以为NULL
                    .clientHandler(new StreamImClientHandler())
                    //客户端事件监听器，可以为null，但建议自己实现该接口
                    .clientListener(new StreamImClientListener())
                    //心跳时长不设置，就不发送心跳包
                    //.heartbeatTimeout(5000)
                    //断链后自动连接的，不想自动连接请设为null
                    //.reConnConf(new ReconnConf(5000L))
                    .build();
            //生成客户端对象;
            SimClient simClient = new SimClient(imClientConfig);
            //连接服务端
            imClientChannelContext = simClient.connect(serverNode);
            //连上后，发条消息玩玩
            byte[] loginBody = new LoginReqBody("system", "system").toByte();
            TcpPacket loginPacket = new TcpPacket(Command.COMMAND_LOGIN_REQ, loginBody);
            //先登录;
            SimClientAPI.send(imClientChannelContext, loginPacket);
        }
    }

    /**
     * 上下麦通知
     * @param message
     */
    public void send(StreamMessageBody message) {
        TcpPacket chatPacket = new TcpPacket(Command.COMMAND_STREAM_REQ, message.toByte());
        SimClientAPI.send(imClientChannelContext, chatPacket);
    }
}
